package com.hospital.yygh.msm.controller;

import com.hospital.yygh.common.result.Result;
import com.hospital.yygh.msm.service.MsmService;
import com.hospital.yygh.msm.utils.RandomUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("/api/msm")
@Slf4j
public class MsmApiController {

    @Autowired
    private MsmService msmService;

    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    /**
     * 弊端，只能是当前手机号，这个是模板，用的时候在注册容联云
     *
     * @param phone
     * @return
     */
    @GetMapping("send/{phone}")
    public Result sendCode(@PathVariable String phone) {
        // 从redis获取验证码，如果获取到，就返回ok
        // key-手机号，value-验证码
        String code = redisTemplate.opsForValue().get(phone);
        if (!StringUtils.isEmpty(code)) {
            return Result.ok();
        }
        // 如果redis获取不到，则生成验证码(随机)
        code = RandomUtil.getSixBitRandom();
        if (msmService.send(phone, code)) {
            redisTemplate.opsForValue().set(phone, code, 5, TimeUnit.MINUTES);
            return Result.ok();
        } else {
            return Result.fail();
        }
    }

    /**
     * 采用QQ邮箱验证码方式
     *
     * @param phone
     * @return
     */
    @GetMapping("sendEmail/{phone}")
    public Result sendEmailCode(@PathVariable String phone) {
        // 从redis获取验证码，如果获取到，就返回ok
        // key-手机号，value-验证码
        String code = redisTemplate.opsForValue().get(phone);
        log.info("获取msm中redis的验证码："+code);
        if (!StringUtils.isEmpty(code)) {
            return Result.ok();
        }
        // 如果redis获取不到，则生成验证码(随机)
        code = RandomUtil.getSixBitRandom();
        log.info("获取utils中RandomUtil随机生成的验证码："+code);
        boolean isSend = msmService.sendEmail(phone, code);
        if (isSend) {
            redisTemplate.opsForValue().set(phone, code, 5, TimeUnit.MINUTES);
            log.info("存放到redis的验证码：" + redisTemplate.opsForValue().get(phone));
            return Result.ok();
        } else {
            return Result.fail().message("发送邮箱失败");
        }
    }


}
